package git.soulbgm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import git.soulbgm.common.base.BaseController;
import git.soulbgm.common.pojo.QueryDto;
import git.soulbgm.common.pojo.Response;
import git.soulbgm.pojo.NodeUsedInfo;
import git.soulbgm.service.NodeUsedInfoService;
import git.soulbgm.utils.EasyPoiUtil;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static git.soulbgm.common.MonitorConstants.REDIS_KEY_NODE_DISK_PREDICT;

/**
 * 节点资源情况控制器
 *
 * @author SoulBGM
 * @date 2022/03/11 10:28
 */
@RestController
@RequestMapping("system/nodeUsed")
public class NodeUsedController extends BaseController {

    private final NodeUsedInfoService nodeUsedInfoService;
    private final HashOperations<String, String, String> opsForHash;

    public NodeUsedController(NodeUsedInfoService nodeUsedInfoService, StringRedisTemplate redis) {
        this.nodeUsedInfoService = nodeUsedInfoService;
        this.opsForHash = redis.opsForHash();
    }

    @PostMapping("list")
    public Response list(@RequestBody QueryDto<NodeUsedInfo> dto, Page<NodeUsedInfo> queryPage) {
        Page<NodeUsedInfo> resultPage = nodeUsedInfoService.page(queryPage, new QueryWrapper<>(dto.getData()));
        return success(resultPage);
    }

    @GetMapping("nodeDiskPredictAll")
    public Response nodeDiskPredictAll() {
        return success(convert(opsForHash.entries(REDIS_KEY_NODE_DISK_PREDICT)));
    }

    /**
     * 获得节点的磁盘预测
     *
     * @param nodeCode 节点编号
     * @return {@link Integer}
     */
    private Integer getNodeDiskPredict(Integer nodeCode) {
        Map<String, String> map = opsForHash.entries(REDIS_KEY_NODE_DISK_PREDICT);
        return Integer.parseInt(map.getOrDefault(String.valueOf(nodeCode), "30"));
    }

    /**
     * 转换
     *
     * @param predictMap 预计Map
     * @return {@link Map}<{@link String}, {@link String}>
     */
    private Map<Integer, Integer> convert(Map<String, String> predictMap) {
        Map<Integer, Integer> convertMap = new HashMap<>(predictMap.size());
        predictMap.forEach((k, v) -> convertMap.put(Integer.parseInt(k), Integer.parseInt(v)));
        return convertMap;
    }

    @GetMapping("export")
    public void export(NodeUsedInfo info, HttpServletResponse response) {
        List<NodeUsedInfo> list = nodeUsedInfoService.list(new QueryWrapper<>(info));
        try {
            EasyPoiUtil.exportExcel(response, "主机状态数据", list, NodeUsedInfo.class);
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }

}
